package com.wsjc.app.push.socket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import com.alibaba.fastjson.JSON;
import com.wsjc.common.core.constants.CommonConst;
import com.wsjc.common.core.entity.ApiCommonResultVo;

/**
 *
 * @author 9373
 */
@Component
public class SystemWebSocketHandler implements WebSocketHandler {

	
//	@Autowired
//	private NoticeServer noticeService;
	
	private static Logger logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
	

	private static final ArrayList<WebSocketSession> users; // 用来存储 登陆的用户
	static {
		users = new ArrayList<>();
	}
	
	@Bean
	public SystemWebSocketHandler systemWebSocketHandler() {
		return new SystemWebSocketHandler();
	}
	

	
	// 任何用户连接成功后，都会调用该方法，进行推送。
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		
		logger.info("PUSH-SCOKET|INFO|init|connect to the websocket success......");
		System.out.println("connect to the websocket success......");
		users.add(session);
		logger.info("PUSH-SCOKET|INFO|init|the users size is " + users.size() + "个用户已建立了连接！");
		System.out.println("List 集合中共有 ：" + users.size() + " 个 用户");
		
		ApiCommonResultVo apiCommonResultVo = new ApiCommonResultVo(1, "连接成功...暂无最新数据上传！",null) ;
		
		String msg = JSON.toJSONString(apiCommonResultVo);
			
		logger.info("PUSH-SCOKET|INFO|init|init msg send to user, the msg content is  " + msg);
		System.out.println("第一次链接获取到的 数据 ：" + msg);
		session.sendMessage(new TextMessage(msg));
			
		/**
		 * 后续可能会从db获取 最新的10条，作为默认展示。
		 */
	}

	
	// 接收客户端输入的数据。。。
	@Override
	public void handleMessage(WebSocketSession wss, WebSocketMessage<?> wsm) throws Exception {
		TextMessage returnMessage = new TextMessage(wsm.getPayload() + " received at server");
		// 讲得到的数据返回给 发过来的客户端
		wss.sendMessage(returnMessage);

		// 给管理员发送消息
		//systemWebSocketHandler().sendMessageToUser("18940982533" , new TextMessage(wsm.getPayload()+""));
		//systemWebSocketHandler().sendMessageToUser("13998641323" , new TextMessage(wsm.getPayload()+""));
	}

	
	/**
     * 消息传输过程中出现的异常处理函数
     * 处理传输错误：处理由底层WebSocket消息传输过程中发生的异常
     */
	@Override
	public void handleTransportError(WebSocketSession wss, Throwable thrwbl) throws Exception {
		if (wss.isOpen()) {
			wss.close();
		}
		users.remove(wss);
		logger.info("PUSH-SCOKET|ERROR|the network hand exception, so this websocket connection closed......" );
		System.out.println("websocket connection closed......");
	}

	
	/**
     * websocket链接关闭的回调
     * 连接关闭后：一般是回收资源等
     */
	@Override
	public void afterConnectionClosed(WebSocketSession wss, CloseStatus cs) throws Exception {

		users.remove(wss);
		logger.info("PUSH-SCOKET|INFO|the user close this connection......" );
		System.out.println("websocket connection closed......");
	}

	// 处理拆分消息。如果发过来的消息过长，将会进行切割。
	@Override
	public boolean supportsPartialMessages() {
		return false;
	}

	/**
	 * 给所有在线用户发送消息
	 *
	 * @param message
	 */
	public void sendMessageToAllUser(TextMessage message) {
		if (null != users) {
			logger.info("PUSH-SCOKET|INFO|send msg to all user......" );
			System.out.println("给所有人发小心 ：由用户存在---");
			for (WebSocketSession user : users) {
				try {
					if (user.isOpen()) {
						user.sendMessage(message);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			logger.info("PUSH-SCOKET|INFO|send msg to all user......but no user have connection" );
			System.out.println("给所有人发小心 ：没有用户存在");

		}
	}

	/**
	 * 给某个用户发送消息
	 *
	 * @param userName
	 * @param message
	 */
	public void sendMessageToUser(String userName, TextMessage message) {
		if (null != users) {
			logger.info("PUSH-SCOKET|INFO|send msg to user......" + userName);
			System.out.println("给某个人发小心：由用户存在---");
			for (WebSocketSession user : users) {
				if (user.getAttributes().get(CommonConst.CURRENT_USER).equals(userName)) {
					try {
						if (user.isOpen()) {
							user.sendMessage(message);
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
					break;
				}
			}
		} else {
			logger.info("PUSH-SCOKET|INFO|send msg to all user......but no user have connection" );
			System.out.println("给某个人发小心：没有用户存在");
		}
	}
	    
	    
	/**
	 * 给指定的一些用户发消息
	 *
	 * @param userName
	 * @param message
	 */
	public void sendMessageToUser(Set<String> usernames, TextMessage message) {
		if (null != users) {
			logger.info("PUSH-SCOKET|INFO|send msg to users......" + usernames.toString() );
			System.out.println("给某个人发小心：由用户存在---");
			for(String username : usernames){
				for (WebSocketSession user : users) {
					if (user.getAttributes().get(CommonConst.CURRENT_USER).equals(username)) {
						try {
							if (user.isOpen()) {
								user.sendMessage(message);
							}
						} catch (IOException e) {
							e.printStackTrace();
						}
						break;
					}
				}
			}
		} else {
			logger.info("PUSH-SCOKET|INFO|send msg to users......but no user have connection" );
			System.out.println("给某个人发小心：没有用户存在");
		}
	}    
	    
}